#clean data
data_exp<-data_student_exp_raw %>%
  group_by(an_adm,liceu_repartizat) %>%
  mutate(Exp_stud=Expenditure/sum(!is.na(id_adm)))
data_teacher<-data_student_teacher_raw


#resource access regressions
model_teacher<-feols(I(teacher_perc*100)~I(entrance_perc*100)+dec_town+n_hs_town_group+dec_town*n_students_town_yr+Unemployment_hs_bac*dec_town+Wages_hs_bac*dec_town+drop_hs_hs_bac*dec_town|
               as.factor(an)+specializare_bac2+scoala_de_provenienta+town|
                 I(school_mean*100)~dec_town*n_hs_town_group,
             cluster=~judet_bac+town,
             data=data_teacher %>% filter(school_change==F))
summary(model_teacher)

model_exp<-feols(Exp_stud~I(entrance_perc*100)+dec_town+n_hs_town_group+dec_town*n_students_town_yr+Unemployment_hs_bac*dec_town+Wages_hs_bac*dec_town+drop_hs_hs_bac*dec_town|
               as.factor(an)+specializare_bac2+scoala_de_provenienta+town|
               I(school_mean*100)~dec_town*n_hs_town_group,
             cluster=~judet_bac+town,
             data=data_exp %>% filter(school_change==F))
summary(model_exp)


#write results
options(modelsummary_format_numeric_latex = "plain")
f_big<-function(x) format(x, big.mark=",", scientific=FALSE, nsmall=1,digits=1)
f <- function(x) format(round(x/1000000,1) , nsmall = 1)

current_path<-rstudioapi::getActiveDocumentContext()$path
setwd(dirname(current_path))
fileConn<-file("08_table_06.txt")
writeLines(
print(modelsummary(list(model_teacher ,
                        model_exp),
                   statistic = "std.error",
                   estimate="{estimate}{stars}",
                   stars=c('$^{*}$'=0.1,'$^{**}$'=0.05,'$^{***}$'=0.01),
                   gof_map=list(list("raw" = "nobs", "clean" = "N", "fmt" = f_big),
                                list("raw" = "r.squared", "clean" = "R$^2$",fmt="%.2f")),
                   metrics="R2",
                   output="latex",
                   fmt=2,
                   escape=F)
), fileConn)
close(fileConn)

#mean number of students; number appears in text
mean<-data_student_raw %>% group_by(liceu_repartizat,an_adm) %>%
  summarise(n=n()) %>%
  filter(!is.na(liceu_repartizat) & liceu_repartizat!='') 

mean(mean$n)
  

